//
//  AppDelegate+AutoLogin.m
//  XiangLove
//
//  Created by 陈宪栋 on 2017/11/28.
//  Copyright © 2017年 BAOMIHUA.COM. All rights reserved.
//

#import "AppDelegate+AutoLogin.h"
#import "XLHTTPSessionManager.h"
#import "XLHTTPSessionManager+Login.h"
#import <ReactiveCocoa.h>
#import "XLAccountManager.h"
#import "XLUserInfoModel.h"
#import "XLNewMainViewController.h"
#import "XLNavgationViewController.h"
#import <objc/runtime.h>

@implementation AppDelegate (AutoLogin)
- (void)autoLoginSuccessBlock:(LoginSuccessBlock)success failBlock:(LoginFailBlock)failBlock {
    
    XLHTTPSessionManager *manager = [XLHTTPSessionManager sharedManager];
    manager.cachePloy = XLHTTPCachePloy_Server;
    [[manager visitorLogin] subscribeNext:^(id x) {
        self.userInfoModel = x;
        [UserDefaults setObject:self.userInfoModel.Id forKey:UserID];
        [UserDefaults setObject:self.userInfoModel.HeadImg forKey:UserHead];
        [UserDefaults setObject:self.userInfoModel.NickName forKey:UserNick];
        [UserDefaults setObject:self.userInfoModel.Token forKey:UserToken];
        [XLHTTPSessionManager attemptDealloc];
        [self loginBoyibo:success failBlock:failBlock];
    } error:^(NSError *error) {
        
        if (failBlock) {
            failBlock(@"");
        }
    }];
}

- (void)refreshSecretKeyWithUserId:(NSString *)userId {
//    XLHTTPSessionManager *manager = [XLHTTPSessionManager sharedManager];
//    manager.cachePloy = XLHTTPCachePloy_Server;
//    [[manager refreshSecretKeyWithUserId:userId] subscribeNext:^(XLUserInfoModel *model) {
//        if ([userId isEqualToString:model.Id]) {
//            self.userInfoModel = model;
//            [UserDefaults setObject:self.userInfoModel.Id forKey:UserID];
//            [UserDefaults setObject:self.userInfoModel.HeadImg forKey:UserHead];
//            [UserDefaults setObject:self.userInfoModel.NickName forKey:UserNick];
//            [[XLAccountManager shareInstance] updateUserInfo:model];
//        }
//    } error:^(NSError *error) {
//
//    }];
}

#pragma mark - 登录腾讯云
- (void)loginBoyibo:(LoginSuccessBlock)success failBlock:(LoginFailBlock)failBlock {
    NSString * useridStr   = self.userInfoModel.Id;
    NSString * boundSource = @"4";
    //时间
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    //令牌
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    
    NSString *sTimeUser = [fmt stringFromDate:now];
    NSString *objIDUser = @"0";
    NSString *publicKeyUser = @"BMH2014YDYWB";
    NSString *natUser = [NSString stringWithFormat:@"%@%@%@%@",objIDUser,useridStr, publicKeyUser, sTimeUser];
    natUser = [natUser md5Encrypt];
    
    NSDictionary * UserInfoDic = [NSDictionary dictionaryWithObjectsAndKeys:@"8",@"Type",useridStr,@"Userid",boundSource,@"Boundsource",locationString,@"Timestamp",natUser,@"Appsign",nil];
//    [BMHHTTPSession GET:@"/MobileInterface/User/UserInfo.ashx" paraments:UserInfoDic success:^(id  _Nullable JSON) {
//        if ([JSON[@"result"][@"errcode"] integerValue] != 0) {
//            [MBProgressHUD showContent:JSON[@"result"][@"errmsg"]];
//            return ;
//        }
//        NSString *sign = JSON[@"result"][@"data"][@"Sign"];
        TIMLoginParam * login_param = [[TIMLoginParam alloc ]init];
        
        // accountType 和 sdkAppId 通讯云管理平台分配
        // identifier为用户名，userSig 为用户登录凭证
        // appidAt3rd 在私有帐号情况下，填写与sdkAppId 一样
    NSString *TXAPPID = TIM_APP_ID_TEST;
    NSString *TXACCOUNTTYPE = TIM_ACCOUNT_TYPE_TEST;
    NSString *xlapi = BaseURL;
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"isTestUrl"]isEqualToString:@"yes"]) {
        xlapi = @"http://test.xinliao.xiuquapp.com";
    }
    if ([xlapi isEqualToString:@"http://xinliao.xiuquapp.com"]) {
        TXAPPID = TIM_APP_ID;   TXACCOUNTTYPE = TIM_ACCOUNT_TYPE;
    }
        login_param.accountType = TXACCOUNTTYPE;
        login_param.identifier = [NSString stringWithFormat:@"%@",self.userInfoModel.Id];
        login_param.userSig = self.userInfoModel.Sign;
        login_param.appidAt3rd = TXAPPID;
        login_param.sdkAppId = [TXAPPID intValue];
        
        [[TIMManager sharedInstance] login:login_param succ:^(){
            
            TIMAPNSConfig * apnsConfig = [[TIMAPNSConfig alloc] init];
            apnsConfig.openPush = 1;
            apnsConfig.c2cSound = @"";;
            
            [[TIMManager sharedInstance] setAPNS:apnsConfig succ:^() {
                DebugLog(@"nnnnnnnnnnnnnn");
            } fail:^(int code, NSString *err) {
                DebugLog(@"setAPNS fail %d %@",code , err);
            }];
            
            //视频聊天ILiveSDK登录
            [[ILiveLoginManager getInstance] iLiveLogin:[NSString stringWithFormat:@"%@",self.userInfoModel.Id] sig:self.userInfoModel.Sign succ:^{
                [[XLAccountManager shareInstance] updateUserInfo:self.userInfoModel];
                if (success) {
                    if ([self.userInfoModel.IsAnchor isEqualToString:@"1"]) {
                        [self joinGroup];
                    }
                    success(@"");
                }
            } failed:^(NSString *moudle, int errId, NSString *errMsg) {
                //登录失败
                if (failBlock) {
                    failBlock(@"");
                }
            }];
        } fail:^(int code, NSString * err) {
            if (failBlock) {
                failBlock(@"");
            }
        }];
//    } failure:^(NSError * _Nullable error) {
//        if (failBlock) {
//            failBlock(@"");
//        }
//    }];
}

- (void)joinGroup {
    [[TIMGroupManager sharedInstance] JoinGroup:@"10086" msg:@"" succ:^{
        [[TIMGroupManager sharedInstance] ModifyGroupMemberInfoSetNameCard:@"10086" user:[[XLAccountManager shareInstance] model].Id nameCard:@"1" succ:^{
        } fail:^(int code, NSString *msg) {
        }];
    } fail:^(int code, NSString *msg) {
        if (code == 10013) {
            [[TIMGroupManager sharedInstance] ModifyGroupMemberInfoSetNameCard:@"10086" user:[[XLAccountManager shareInstance] model].Id nameCard:@"1" succ:^{
            } fail:^(int code, NSString *msg) {
            }];
        } else {
            [MBProgressHUD showContent:@"加群失败"];
        }
    }];
}

- (void)setUserInfoModel:(XLUserInfoModel *)userInfoModel {
    objc_setAssociatedObject(self, @"userInfoModel", userInfoModel, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (XLUserInfoModel *)userInfoModel {
    return objc_getAssociatedObject(self, @"userInfoModel");
}

@end
